<!--
 * @Descripttion: 关联渠道
 * @Author: 颜博骏 bojun@ssc-hn.com
 * @Date: 2024-04-10
 * @LastEditors: 何伟伦 weilun@ssc-hn.com
 * @LastEditTime: 2024-04-16
-->
<template>
  <div>
    <a-modal v-model:visible="visible" title="关联渠道" @ok="onOk" :ok-button-props="{ disabled: !checkValue }" @cancel="emits('update:visible', false)">
      <a-tree-select :fieldNames="{ children: 'children', label: 'channelName', value: 'channelId' }" v-model:value="checkValue" tree-data-simple-mode style="width: 100%" :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }" :tree-data="treeData" placeholder="请选择渠道" :load-data="onLoadData" />
    </a-modal>
  </div>
</template>

<script setup lang="ts">
  import type { TreeSelectProps } from 'ant-design-vue'
  import { computed, ref, watch } from 'vue'

  import { requestAssociateChannel } from '/@/api/business/tracecode/batchChannel'
  import { requestFirstChannel, requestSubChannel } from '/@/api/business/tracecode/channel'
  import { HttpCodeEnum } from '/@/enums/httpEnum'

  const checkValue = ref(null)
  const treeData = ref<TreeSelectProps['treeData']>([])

  const props = defineProps({
    visible: { type: Boolean, default: false },
    batchId: { type: Number, default: null },
  })
  const emits = defineEmits(['update:visible', 'close'])
  const visible = computed({
    get: () => props.visible,
    set: (val) => emits('update:visible', val),
  })

  /**
   * 初始化一级列表
   */
  const initChannel = async () => {
    const { responseCode, responseData } = await requestFirstChannel({})
    if (responseCode === HttpCodeEnum.SUCCESS) {
      treeData.value = responseData.map((item) => {
        return { ...item, isLeaf: item.subCount ? false : true, pId: 0, id: item.channelId }
      })
    }
  }

  watch(visible, () => {
    if (visible.value) {
      initChannel()
    } else {
      checkValue.value = null
      treeData.value = []
    }
  })

  /** 加载子节点 */
  const onLoadData = async (treeNode) => {
    const { id } = treeNode.dataRef
    const { responseCode, responseData } = await requestSubChannel({ channelId: id })
    if (responseCode === HttpCodeEnum.SUCCESS) {
      const data = responseData.map((item) => {
        return { ...item, isLeaf: item.subCount ? false : true, pId: id, id: item.channelId }
      })
      data.forEach((item) => {
        treeData.value = treeData.value.concat({ ...item })
      })
    }
  }

  const onOk = async () => {
    if (checkValue.value) {
      const { responseCode } = await requestAssociateChannel({ channelId: checkValue.value, batchId: props.batchId })
      if (responseCode === HttpCodeEnum.SUCCESS) {
        emits('update:visible', false)
        emits('close', false)
      }
    }
  }
</script>

<style scoped></style>
